package concurrent

import (
	"gitee.com/hongzhaomin/hzm-common-go/strutil"
)

func NewGoroutineLocal[T any]() *GoroutineLocal[T] {
	return &GoroutineLocal[T]{
		gid2UserMap: NewMap[string, T](),
	}
}

// GoroutineLocal 协程map对象，注意协程用完要清除掉，否则容易内存泄漏
type GoroutineLocal[T any] struct {
	gid2UserMap *Map[string, T]
}

func (my *GoroutineLocal[T]) Get() T {
	var t T
	currentGid := strutil.GetCurrentGid()
	if value, ok := my.gid2UserMap.Load(currentGid); ok {
		t = value
	}
	return t
}

func (my *GoroutineLocal[T]) Set(value T) {
	currentGid := strutil.GetCurrentGid()
	my.gid2UserMap.Store(currentGid, value)
}

func (my *GoroutineLocal[T]) Remove() {
	currentGid := strutil.GetCurrentGid()
	my.gid2UserMap.Delete(currentGid)
}
